package com.atguigu.springcloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.atguigu.springcloud.entity.Dept;
import com.atguigu.springcloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

/**
 * 演示服务熔断/断路器
 * 
 * @author ZJie
 * @date 2019年11月4日 下午2:42:42
 */
@RestController
public class DeptController {

	@Autowired
	private DeptService service;
	
	@RequestMapping(value="/dept/get/{id}", method=RequestMethod.GET)
	// 一旦调用服务失败并抛出了错误信息后，会自动调用@HystrixCommand标注好的fallbackMethod指定的方法
	@HystrixCommand(fallbackMethod = "processHystrix_Get")
	public Dept get(@PathVariable("id") Long id) {
		Dept dept = service.get(id);
		// 演示：当为null时，触发服务熔断，手动抛出异常
		if (null == dept) {
			throw new RuntimeException("该ID:" + id + "没有对应的信息");
		}
		return dept;
	}
	
	/**
	 * 容错方法,熔断器,出错后执行
	 */
	public Dept processHystrix_Get(@PathVariable("id") Long id) {
		return new Dept().setDeptno(id)
				.setDname("该ID:" + id + "没有对应的信息,null--@HystrixCommand")
				.setDb_source("no this database in MySQL");
	}
}
